<script setup>
import dayjs from 'dayjs'
import CloneDeep from 'lodash-es/cloneDeep.js'
import { computed, onMounted, ref, watch } from 'vue'

const props = defineProps({
  columns: {
    type: Array,
    default: () => [
      {
        type: 'input',
        label: '标题',
        field: 'keyword',
        placeholder: '请输入关键字',
        hidden: false,
      },
    ],
  },
  initData: {
    type: Object,
    default: () => ({}),
  },
  isResetButton: {
    type: Boolean,
    default: true,
  },
  loading: {
    type: Boolean,
    default: false,
  },
  onFinish: {
    type: Function,
    default: () => {},
  },
  labelWidth: {
    type: [String, Number],
    default: '85px',
  },
})

const emit = defineEmits(['search', 'reset'])

const formValues = ref({})
const formRef = ref()

const isExpanded = ref(false)

// 展示前 3 项，展开显示全部
const visibleColumns = computed(() => {
  return isExpanded.value ? props.columns : props.columns.slice(0, 4)
})

function toggleExpand() {
  isExpanded.value = !isExpanded.value
}

onMounted(() => {
  formValues.value = CloneDeep(props.initData)
})

watch(() => props.initData, (val) => {
  formValues.value = CloneDeep(val)
}, { deep: true })

function searchForm(formEl) {
  if (!formEl) { return }

  const fields = JSON.parse(JSON.stringify(formValues.value))
  props.columns.forEach((item) => {
    if (item.type === 'date' && fields[item.field]) {
      fields[item.field] = dayjs(fields[item.field]).format(item.format || 'YYYY-MM-DD')
    }
    else if (item.type === 'daterange' && fields[item.field]) {
      fields[item.field] = [
        dayjs(fields[item.field][0]).format(item.format || 'YYYY-MM-DD'),
        dayjs(fields[item.field][1]).format(item.format || 'YYYY-MM-DD'),
      ]
    }
  })

  emit('search', fields)
}

function resetForm(formEl) {
  if (!formEl) { return }

  formEl.resetFields()
  formValues.value = {}
  emit('search', JSON.parse(JSON.stringify(formValues.value)))
}
</script>

<template>
  <el-card shadow="never">
    <el-form
      ref="formRef"
      :model="formValues"
      :label-width="labelWidth"
      label-position="left"
      class="w-full"
      @keyup.native.enter="searchForm(formRef)"
    >
      <!-- 表单项区域 -->
      <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-2 w-full">
        <el-form-item
          v-for="(item, index) in visibleColumns"
          :key="item.field"
          :prop="item.field"
          :label="item.label"
        >
          <template v-if="item.type === 'input'">
            <el-input
              v-model.trim="formValues[item.field]"
              :placeholder="item.placeholder || `请输入${item.label}`"
              :style="item.style || 'width:100%'"
              :disabled="item.disabled"
              clearable
            />
          </template>
          <template v-if="item.type === 'select'">
            <el-select
              v-model.trim="formValues[item.field]"
              :placeholder="item.placeholder || `请选择${item.label}`"
              :style="item.style || 'width:100%'"
              :disabled="item.disabled"
              clearable
              :filterable="item.filterable ?? true"
            >
              <el-option
                v-for="s in item.options?.data"
                :key="s[item.options?.key || 'value']"
                :label="s[item.options?.label || 'label']"
                :value="s[item.options?.value || 'value']"
              />
            </el-select>
          </template>
          <template v-if="item.type === 'date'">
            <el-date-picker
              v-model.trim="formValues[item.field]"
              :placeholder="item.placeholder || '请选择日期'"
              :type="item.dateType"
              :style="item.style || 'width:100%'"
              :disabled="item.disabled"
              clearable
            />
          </template>
          <template v-if="item.type === 'daterange'">
            <el-date-picker
              v-model.trim="formValues[item.field]"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :range-separator="item.rangeSeparator || '-'"
              :style="item.style || 'width:100%'"
              :format="item.format"
              :disabled="item.disabled"
              clearable
            />
          </template>
          <template v-if="item.type === 'autocomplete'">
            <el-autocomplete
              v-model.trim="formValues[item.field]"
              :placeholder="item.placeholder || `请输入${item.label}`"
              :fetch-suggestions="item.fetchSuggestions"
              :trigger-on-focus="item.triggerOnFocus ?? true"
              :disabled="item.disabled"
              :clearable="item.clearable ?? true"
              class="w-full"
              @select="(val) => item.onSelect?.(val)"
            >
              <template v-if="item.customTemplate" #default="{ item }">
                <div>{{ item.value }} - {{ item.name }}</div>
              </template>
            </el-autocomplete>
          </template>
          <template v-if="item.type === 'slot'">
            <slot :name="item.slotName" :model="formValues" :field="item.field" />
          </template>
        </el-form-item>
      </div>
      <!-- 底部按钮区域 -->
      <div class="w-full flex justify-end space-x-3 items-center">
        <el-button type="primary" icon="Search" :loading="loading" @click="searchForm(formRef)">
          搜索
        </el-button>

        <el-button v-if="props.isResetButton" icon="Refresh" @click="resetForm(formRef)">
          重置
        </el-button>

        <el-button v-if="props.columns.length > 4" type="text" @click="toggleExpand">
          {{ isExpanded ? '收起' : '展开' }}
          <i :class="isExpanded ? 'el-icon-arrow-up' : 'el-icon-arrow-down'" />
        </el-button>
      </div>
    </el-form>
  </el-card>
</template>
